//
//  BRPaymentViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/30.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRPaymentViewController.h"
#import "BRPaymentDetailView.h"
#import "BRCardListTableViewCell.h"
#import "BRPayStatusViewController.h"
#import "UICountingLabel.h"
#import "BRRentingViewController.h"
#import "BRPayDetailPopView.h"
#import "BRCouponUseListView.h"
#import "GXJWebViewController.h"
#import "standard-Swift.h"

@interface BRPaymentViewController ()<QMUITableViewDelegate,QMUITableViewDataSource,STPAuthenticationContext>
{
    QMUILabel *_symboL;
    QMUILabel *_balanceL;
    QMUILabel *_dueToL;
    QMUILabel *_couponSelL; // 优惠券选择后显示内容
    NSInteger _cardSelectIndex;
    UIView *_payBgView;
    
    UIButton *_policyBtn;
    QMUIButton *_submitBtn;
}

@property (nonatomic,strong) UIView *couponBgView;

@property (nonatomic,strong) BRPayDetailPopView *detailView;

@property (nonatomic,strong) BRPaymentDetailView *addCardView;

@property (nonatomic,strong) BRPaymentDetailView *depositView;

@property (nonatomic,strong) BRCouponUseListView *couponView;

@property (nonatomic,strong) BRPaymentModel *paymentModel;

@property (nonatomic,strong) QMUILabel *taxLb;

@property (nonatomic,assign) BOOL isPayWithCard;

@property (nonatomic,strong) NSMutableArray *cardList;

@property (nonatomic,strong) NSMutableArray *couponsList;

@property (nonatomic,strong) NSString *cardLastNum;

@property (nonatomic,strong) BRCouponModel *selCouponModel;
/// 记录是否展示优惠券，请求接口
@property (nonatomic,assign) BOOL hasCoupon;
/// 是否有刷新数据 才给打开详情
@property (nonatomic,assign) BOOL hasUpadate;

@property (nonatomic,assign) BOOL isFree;

@end

@implementation BRPaymentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.couponsList = [NSMutableArray array];
    self.cardLastNum = @"";
    _cardSelectIndex = -1;
    self.cardList = [NSMutableArray array];
    [self setUI];
    if (self.payType == BRPAY_Deposit || self.payType == BRPAY_Coupon) {
        [self req_cardList];
    }else {
        // 先算钱再获取
        [self req_payAmount];
    }
    
    [self br_blockAction];
    
  
}

#pragma mark - Request --
- (void)req_cardList {
    
    NSString *url = [BRAPI cardPayList:self.payType amount:self.amount.floatValue];
    
    [[BRRequestManager shared] GET:url params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        NSDictionary *dic = dataDict[@"data"];
        NSArray *cardList = [BRCardModel mj_objectArrayWithKeyValuesArray:dic[@"cardList"]];
        self.cardList = [NSMutableArray arrayWithArray:cardList];
        if ([dic[@"apple"] boolValue]) {
            BRCardModel *modl = [self customPay:@"Apple" type:@"3"];
            [self.cardList addObject:modl];
        }
//        if ([dic[@"apple"] boolValue]) {
//            BRCardModel *modl = [self customPay:@"ZaloPay E-Wallet" type:@"7"];
//            [self.cardList addObject:modl];
//            BRCardModel *modl2 = [self customPay:@"MoMo E-Wallet" type:@"8"];
//            [self.cardList addObject:modl2];
//        }
        if (self.cardList.count != 0) {
            self->_cardSelectIndex = 0;
        }
        
        [self.tableView reloadData];
        
        if (self.hasCoupon) {
            [self req_myCoupon];
        }
        
        [self br_updateDetailView];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        
    }];
}

- (BRCardModel *)customPay:(NSString *)name type:(NSString *)type {
    BRCardModel *model = [[BRCardModel alloc] init];
    model.bankName = name;
    model.bankNo = @"--";
    model.defaulted = 0;
    model.expire = 0;
    model.bankType = type;
    
    return model;
}

- (void)req_payAmount {
        
    //    if (!self.dto) return;
    
    NSMutableDictionary *priceDic = [NSMutableDictionary dictionary];
    if (self.dto) priceDic[@"orderNo"] = self.dto.orderNo;
    priceDic[@"type"] = @(self.payType);
  
    
    [[BRPayManager share] paymentAmount:priceDic succ:^(NSDictionary * _Nonnull dataDic) {
        
        BROrderDetailModel *orderDto = [BROrderDetailModel mj_objectWithKeyValues:dataDic[@"data"]];
        self.amount = orderDto.money;
        self->_balanceL.text = [BRPayManager br_amount:orderDto.money];
//        if (self.payType == BRPAY_ChargeCard) {
//            self.taxLb.text = [NSString stringWithFormat:@"(%@ %.2f%%)",Localized(@"pay_includingTax"),orderDto.tax];
//            self.taxLb.hidden = orderDto.tax == 0;
//        }

        self.dto = orderDto;
//        self.detailView = self.dto;
        [self req_cardList];
        
    } faile:^(NSInteger errCode)  {
        
    }];
    
}


- (void)requeNewAmount {
    
    [BRHud showHud];
    [[BRRequestManager shared] POST:[BRAPI inviteReward] params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        [BRHud hidden];
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hidden];
    }];
}

- (void)req_myCoupon {
    
    if (!self.dto) return;
    [self.couponView requestMyCoupon:self.dto.orderNo hasCoupon:^(BOOL has) {
        self->_couponSelL.text = Localized(@"payment_noCoupon");
    }];
    
}

- (void)req_changeBanne:(BRCouponModel *)dto  isSel:(BOOL)isSel {
    self.selCouponModel = dto;
    NSDecimalNumber *new  = self.amount;
    NSString *str = Localized(@"payment_choose");
    
    if (isSel) {
        NSMutableDictionary *priceDic = [NSMutableDictionary dictionary];
        priceDic[@"orderNo"] = self.dto.orderNo;
        priceDic[@"userCouponId"] = [NSString stringWithFormat:@"%ld",dto.userCouponId];
        priceDic[@"type"] = @(self.payType);
        [[BRPayManager share] paymentAmount:priceDic succ:^(NSDictionary * _Nonnull dataDic) {
            
            BROrderDetailModel *orderDto = [BROrderDetailModel mj_objectWithKeyValues:dataDic[@"data"]];
            
            self->_balanceL.text = [BRPayManager br_amount:orderDto.money];
            
//            self.detailView.amount = orderDto.money.floatValue;
            self.dto = orderDto;
            
            [self br_updateDetailView];
            
            
        } faile:^(NSInteger errCode)  {
            
        }];
//        new = [self decimalSub:dto];
//        [self detailCouponAmountUpdate:dto];//更新金额展示
        NSInteger couponType = dto.deductionType;
        NSString *couponsTypeStr = [BRStringTools br_couponsTypeStr:couponType];
        NSString *couponContent = [BRStringTools br_couponsTypeContentV2:dto.deduction];
        str = [NSString stringWithFormat:@"%@ %@",couponsTypeStr,couponContent];
//        str = dto.title;
    }else {
//        self.detailView.couponAmount = 0.0;
//        self.detailView.amount = new.floatValue;
        _balanceL.text = [BRPayManager br_amount:new];
    }

    _couponSelL.text = str;
    
}

//- (void)detailCouponAmountUpdate:(BRCouponModel *)dto {
    
//    CGFloat couponAmount = 0.; //用于订单详情展示优惠券优惠金额
//    if (dto.deductionType == 3) {
//        // 如果是折扣
//        couponAmount = self.dto.orderAmount.floatValue * (100 - dto.discount) / 100.0;
//        
//    }else {
//        couponAmount = dto.amount.floatValue;
//    }
   
//    self.detailView.couponAmount = couponAmount;
//}


#pragma mark - ACTION --
- (void)br_blockAction {
    
    WS(weakSelf);
    self.detailView.hiddenBlock = ^{
        weakSelf.navView.popView.hidden = NO;
    };
    
    self.couponView.itemSelBlock = ^(BRCouponModel * _Nonnull selDto, BOOL isSel) {
        
        [weakSelf req_changeBanne:selDto isSel:isSel];
    };
}

- (void)showOrderDetail {
   
    if (self.payType == BRPAY_Deposit ) {
        if (self.payType == BRPAY_LOST) self.depositView.isLost = YES;
        [self.depositView show];
        return;
    }
    
    if (!self.hasUpadate) return;
    if (!self.detailView.hidden) {
        [self.detailView hidden];
        return;
    }

    [self.detailView show];
    self.navView.popView.hidden = YES;
}

- (void)clickPolicyBtn:(UIControl *)btn {
    _policyBtn.selected = !_policyBtn.selected;
    _submitBtn.enabled = _policyBtn.selected;
}

- (void)toPolicy {
    NSString *url =  USERManager.depositPolicy ;
    NSString *titleStr = Localized(@"agreement_depositTitle");
    url = [NSString stringWithFormat:@"%@?lang=%@",url,[BRLanguageManager share].language];
    GXJWebViewController *webView = [[GXJWebViewController alloc] init];
    webView.url = url ;
    [webView initWhiteBarWithTitle:titleStr isBack: YES];
    webView.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:webView animated:YES completion:nil];
}



- (void)payStatus:(BRPAY_STAUS)status by:(BRPaymentModel *)dto {
    
//    if (status == BRPAY_SUCC) {
//        
//        if (self.payType == BRPAY_Deposit) {
//            // 先押金去租借
//            BRRentingViewController *vc = [[BRRentingViewController alloc] init];
//            vc.orderNo = dto.orderNo;
//            [self.navigationController pushViewController:vc animated:YES];
//            return;
//        }
//        
//        
//    }
    // 租借中购买成功后与其他一样处理
    BRPayStatusViewController *vc = [[BRPayStatusViewController alloc] init];
    vc.status = status;
    vc.dto = dto;
    vc.orderDto = self.dto;
    vc.isFree = self.isFree;
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)goToPay {
    
    [BRHud showInView:self.view];
    
    
    [self req_payFirst:^(id dic) {
        [self br_payNext:(NSMutableDictionary *)dic];
    }];
    
//    NSLog(@"%@",@(self.isPayWithCard));
//    
//    if (_cardSelectIndex == -1 && !self.isPayWithCard) {
//        
//        [BRHud showAuto:Localized(@"Dialog_SelectPayment_Message") inView:self.view];
//        NSLog(@"请先选择支付方式");
//        return;
//    }
//    
//    [BRHud showInView:self.view];
//    
//    
//    NSInteger type = self.payType;
//    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"type":@(type)}];
//    if (self.payType == BRPAY_Rent || self.payType == BRPAY_LOST || self.payType == BRPAY_BuyPB) {
//        dic[@"orderNo"] = self.dto.orderNo;
//    }
//    if (self.payType == BRPAY_Coupon) {
//        dic[@"couponId"] = self.itemId;
//    }
//    if (self.sno.length != 0) {
//        dic[@"cabinetNo"] = self.sno;
//    }
//    
//    
//    if (self.isPayWithCard) {
//        //输卡后支付
//        dic[@"payType"] = @"1";
//        dic[@"cardToken"] = @"";
//        
//        if (!self.addCardView.cardParams) {
//            
//            [BRHud hiddenInView:self.view];
//            return;
//        }
//        
//        [self payAddCard:dic];
//        return;
//    }
//    
//    BRCardModel *modl = self.cardList[_cardSelectIndex];
//    if ([modl.bankType isEqualToString:@"3"]) {
//        
//        // 苹果支付
//        dic[@"payType"] = modl.bankType;
//        [BRPayManager share].dic = dic;
//        
//        NSMutableDictionary *priceDic = [NSMutableDictionary dictionary];
//        priceDic[@"orderNo"] = self.dto.orderNo;
//        priceDic[@"type"] = @(self.payType);
//        if (self.selCouponModel) {
//  
//            priceDic[@"userCouponId"] = [NSString stringWithFormat:@"%ld",self.selCouponModel.userCouponId];
//        }
//        NSString *orderNo = self.dto.orderNo;
//        
//        if (orderNo.length != 0) {
//            
//            // 优先计算需要支付的金额
//            [[BRPayManager share] paymentAmount:priceDic succ:^(NSDictionary * _Nonnull dataDic) {
//
//                BROrderDetailModel *orderDto = [BROrderDetailModel mj_objectWithKeyValues:dataDic[@"data"]];
//                
//                if (orderDto.isFree) {
//                    
//                    dic[@"payType"] = @(-1);//存在优惠券扣款后 最低金额问题
//                    
//                    [self payFree:orderDto.money dic:dic];
//                }else {
//                    [self payApplePay:orderDto.money];
//                }
//                
//
//            } faile:^(NSInteger errCode) {
//
//                [BRHud hiddenInView:self.view];
//            }];
//            
//        }else {
//           
//            // 无订单无法计算金额
//            [self payApplePay:self.amount];
//        }
//        
//        return;
//    }else {
//        
//        self.cardLastNum = modl.bankNo;
//        // 有卡支付
//        dic[@"payType"] = @"0";
//        dic[@"customerId"] = modl.customerId;
//        
//    }
//    
//    
//    [self pay:dic];
    
}

/// 检测低消
- (void)req_payFirst:(BRIDBlock)nextBlock {
    
    self.isFree = NO;
    NSInteger type = self.payType;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"type":@(type)}];
    if (self.payType == BRPAY_Rent || self.payType == BRPAY_LOST || self.payType == BRPAY_BuyPB) {
        dic[@"orderNo"] = self.dto.orderNo;
    }
    if (self.payType == BRPAY_Coupon) {
        dic[@"couponId"] = self.itemId;
    }
    if (self.sno.length != 0) {
        dic[@"cabinetNo"] = self.sno;
    }
    if (self.selCouponModel) {
        
        dic[@"userCouponId"] = [NSString stringWithFormat:@"%ld",self.selCouponModel.userCouponId];
    }
    dic[@"paymentChannel"] = @"stripe";
    
    if (!(self.payType == BRPAY_Deposit || self.payType == BRPAY_Coupon)) {
        // 计算金额 小于0.5直接支付
        [self req_computePayAmount:dic next:^{
            
            nextBlock(dic);
        }];
        
    }else {
        nextBlock(dic);
    }
}

- (void)req_computePayAmount:(NSDictionary *)payDic next:(BRVoidBlock)payNext {
    
    NSMutableDictionary *priceDic = [NSMutableDictionary dictionary];
    priceDic[@"orderNo"] = self.dto.orderNo;
    priceDic[@"type"] = @(self.payType);
    if (self.selCouponModel) {
        
        priceDic[@"userCouponId"] = [NSString stringWithFormat:@"%ld",self.selCouponModel.userCouponId];
    }
    // 优先计算需要支付的金额
    [[BRPayManager share] paymentAmount:priceDic succ:^(NSDictionary * _Nonnull dataDic) {
        
        BROrderDetailModel *orderDto = [BROrderDetailModel mj_objectWithKeyValues:dataDic[@"data"]];
        
        if (orderDto.isFree) {
            self.isFree = YES;
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:payDic];
            dic[@"payType"] = @(-1);//存在优惠券扣款后 最低金额问题 支付类型为-1
            [self payFree:orderDto.money dic:dic];
            
            return;
        }
        
        if (payNext) {
            payNext();
        }
        
    } faile:^(NSInteger errCode) {
        
        [BRHud hiddenInView:self.view];
    }];
}

- (void)br_payNext:(NSMutableDictionary *)dic {
    NSLog(@"%@",@(self.isPayWithCard));
    
    if (_cardSelectIndex == -2 && !self.isPayWithCard) {
        [BRHud hiddenInView:self.view];
        [BRHud showAuto:Localized(@"Dialog_SelectPayment_Message") inView:self.view];
        NSLog(@"请先选择支付方式");
        return;
    }
    
    if (self.isPayWithCard) {
        //输卡后支付
        dic[@"payType"] = @"1";
        dic[@"bankcardInfo"] = @{};
        
        if (!self.addCardView.cardParams) {
            
            [BRHud hiddenInView:self.view];
            return;
        }
        
        [self payAddCard:dic];
        return;
    }
    BRCardModel *modl = self.cardList[_cardSelectIndex];
    if (!modl) {
        NSLog(@"支付选择错误");
    }
    if ([modl.bankType isEqualToString:@"3"]) {

        if (![[BRPayManager share] isSupportApplePay]) {
            NSLog(@"添加app pay");
            [BRHud hiddenInView:self.view];

            BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"public_notice") subTitle:Localized(@"payment_applePayAddMsg") cancelStr:Localized(@"public_notNow") succStr:Localized(@"public_confirm") cancelAction:^{

            } successAction:^{
                [BROpenURL openWallet];
            } showBC:YES];

            [self.view addSubview:alertV];

            return;
        }
        // 苹果支付
        dic[@"payType"] = modl.bankType;
        [BRPayManager share].dic = dic;

        NSMutableDictionary *priceDic = [NSMutableDictionary dictionary];
        priceDic[@"orderNo"] = self.dto.orderNo;
        priceDic[@"type"] = @(self.payType);
        if (self.selCouponModel) {

            priceDic[@"userCouponId"] = [NSString stringWithFormat:@"%ld",self.selCouponModel.userCouponId];
        }
        NSString *orderNo = self.dto.orderNo;

        if (orderNo.length != 0) {

            // 优先计算需要支付的金额
            [[BRPayManager share] paymentAmount:priceDic succ:^(NSDictionary * _Nonnull dataDic) {

                BROrderDetailModel *orderDto = [BROrderDetailModel mj_objectWithKeyValues:dataDic[@"data"]];

                if (orderDto.isFree) {
                    self.isFree = YES;
                    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:priceDic];
                    dic[@"payType"] = @(-1);//存在优惠券扣款后 最低金额问题 支付类型为-1
                    [self payFree:orderDto.money dic:priceDic];
                    
                    return;
                }
                
                [[BRPayManager share] applePay:orderDto.money];


            } faile:^(NSInteger errCode) {

                [BRHud hiddenInView:self.view];
            }];

        }else {

            // 无订单无法计算金额
            [[BRPayManager share] applePay:self.amount];
        }


        //苹果支付回调
        WS(weakSelf);
        [BRPayManager share].applePayBlock = ^(BRPAY_STAUS status, BRPaymentModel * _Nonnull dto) {
            [weakSelf payStatus:status by:dto];
        };

        return;
    }
//    else {
        
    self.cardLastNum = modl.bankNo;
    // 有卡支付
    dic[@"payType"] = @"0";
    dic[@"customerId"] = modl.customerId;
    dic[@"bankcardId"] = modl.cardId;
//    dic[@"bankcardInfo"] = [modl mj_keyValues];
//        dic[@"paymentChannel"] = modl.paymentChannel;
//    }
    
    
    [self pay:dic];
}

- (void)payApplePay:(NSDecimalNumber *)money  {
    
    if (![[BRPayManager share] isSupportApplePay]) {
        NSLog(@"添加app pay");
        [BRHud hiddenInView:self.view];
        
        BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"public_notice") subTitle:Localized(@"payment_applePayAddMsg") cancelStr:Localized(@"public_notNow") succStr:Localized(@"profile_confirm") cancelAction:^{
            
        } successAction:^{
            [BROpenURL openWallet];
        } showBC:YES];
        
        [self.view addSubview:alertV];
        
        return;
    }
    
    [[BRPayManager share] applePay:money];
    
    //苹果支付回调
    WS(weakSelf);
    [BRPayManager share].applePayBlock = ^(BRPAY_STAUS status, BRPaymentModel * _Nonnull dto) {
        [weakSelf payStatus:status by:dto];
    };
    
}

- (void)payFree:(NSDecimalNumber *)amount dic:(NSDictionary *)dic {
    
    WS(weakSelf);
    BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:@"" subTitle:Localized(@"pay_freeTips") cancelStr:Localized(@"public_cancel") succStr:Localized(@"public_confirm") cancelAction:^{
        [BRHud hidden];
    } successAction:^{
        NSLog(@"确定");
        [weakSelf pay:dic];
    } showBC:YES];
  
    
    [self.view addSubview:alertV];
}


- (void)payAddCard:(NSDictionary *)dic {
    
    NSMutableDictionary *dict = [NSMutableDictionary  dictionaryWithDictionary:dic];
    [[BRPayManager share] checkCard:self.addCardView.cardParams isDefault:self.addCardView.isDefault succ:^(BRAddCardModel * _Nonnull addModel) {
        
        NSString *bankNo = self.addCardView.cardParams.number;
        if (bankNo.length > 4) {
            self.cardLastNum = [bankNo substringFromIndex:bankNo.length - 4];
        }else {
            self.cardLastNum  = bankNo;
        }
        NSMutableDictionary *dickey = [addModel mj_keyValues];
        
        dickey[@"save"] = self.addCardView.isAdd ? @1 : @0;
        dickey[@"bankNo"] = self.cardLastNum; //改后4
        dickey[@"paymentChannel"] = @"stripe";
        dict[@"bankcardInfo"] = dickey;
        dict[@"cardToken"] = addModel.token;
        if (self.addCardView.cardParams.addressZip) {
            dict[@"postalCode"] = self.addCardView.cardParams.addressZip;
        }
        
        [self pay:dict];
        
    } faile:^{
        [BRHud hiddenInView:self.view];
    }];
    

}

- (void)pay:(NSDictionary *)params {
    
    [[BRPayManager share] paymentCardWithParams:params succ:^(NSDictionary * _Nonnull dic) {
        
        
        
        BRPaymentModel *model = [BRPaymentModel mj_objectWithKeyValues:dic[@"data"]];
        model.bankNo = self.cardLastNum;
        NSInteger succ = model.success;
        if (succ == 1) {
            //成功
            [BRHud hiddenInView:self.view];
            
            if (self.addCardView.isAdd || self.addCardView.isDefault) {
                self->_cardSelectIndex = -1;
                [self req_cardList];
                
            }
            
            NSLog(@"支付成功");
            
            [self payStatus:BRPAY_SUCC by:model];
            
            return;
            
        }
        if (succ == 3) {
            // 需要校验
            
            if (model.clientSecret.length != 0) {
                
                self.paymentModel = model;
                
                [self sent3Dmethod:model.clientSecret];
                
            }
            return;
        }
        if (succ == 2) {
            //失败
            [BRHud hiddenInView:self.view];
            [self payStatus:BRPAY_FAILED by:model];
            
            return;
        }
        
    } faile:^(NSInteger code, NSString * _Nonnull errMsg) {
        
        
        [BRHud hiddenInView:self.view];
    }];
}

- (void)toScanCard {
    
    WS(weakSelf);
    [[BRScanCardSwift shared] presentSheet:self succ:^(NSString * _Nonnull cardNum) {
        
        STPPaymentMethodCardParams *cardParam = [[STPPaymentMethodCardParams alloc] init];
        cardParam.number = cardNum;
        weakSelf.addCardView.paymentMethodCardParams = cardParam;
    } fail:^(NSString * _Nonnull failStr) {
        
        [BRHud showAuto:failStr inView:weakSelf.view];
    }];
}

- (BOOL)isPayWithCard {
    return !self.addCardView.isHidden;
}

/// 导航右边点击
- (void)insClick {
    
}
/// 打开优惠券
- (void)toCouponList {
    
    if (self.detailView) {
        [self.detailView hidden];
    }
    
    [self.view bringSubviewToFront:self.couponView];
    // 展开优惠券列表
    [self.couponView show];
}

- (void)toCardPay {
    
    [self.addCardView show];
    [self.addCardView br_becomeFirst];
    [self.view bringSubviewToFront:self.addCardView];
    [self.view bringSubviewToFront:_payBgView];
    WS(weakSelf);
    self.addCardView.toScan = ^{
        [weakSelf toScanCard];
    };
}


- (void)br_updateDetailView {
    
    BROrderDetailModel *dto = self.dto;
    if (!dto) return;
    if (!self.detailView) return;
    
    self.hasUpadate = YES;

    BOOL hasTax = dto.tax > 0;
    if (self.payType == BRPAY_Deposit) {
        hasTax = NO;
    }

    NSString *title0 = [NSString stringWithFormat:@"%@: ",Localized(@"charge_card")];
    NSString *title1 = [NSString stringWithFormat:@"%@: ",Localized(@"menu_coupon")];
    NSString *title1_1 = [NSString stringWithFormat:@"%@: ",Localized(@"pay_promoCode")];
    NSString *title2 = [NSString stringWithFormat:@"%@: ",Localized(@"order_discount")];
//    NSString *title3 = [NSString stringWithFormat:@"%@: ",Localized(@"pay_feesAfterDiscount")];
//    NSString *title5 = [NSString stringWithFormat:@"%@: ",Localized(@"order_amount2bePaid")];
    NSString *title6 = [NSString stringWithFormat:@"%@: ",Localized(@"order_orderID")];
    NSString *title7 = [NSString stringWithFormat:@"%@: ",Localized(@"order_rentalDate")];
    NSString *title8 = [NSString stringWithFormat:@"%@: ",Localized(@"order_retrurnDate")];
    NSString *title9 = [NSString stringWithFormat:@"%@: ",Localized(@"home_duration")];
    
    NSString *title10 = [NSString stringWithFormat:@"%@: ",Localized(@"order_orderAmount")];
    
    NSString *taxTitle = [NSString stringWithFormat:@"%@ %.2f%%: ",Localized(@"pay_tax"),dto.tax];
    NSString *taxInTitle = [NSString stringWithFormat:@"%@: ",Localized(@"order_paymentAmount")];
    if (hasTax) { 
        taxInTitle = [NSString stringWithFormat:@"%@ (%@): ",Localized(@"order_paymentAmount"),Localized(@"pay_includingTax")];
    }
    
    NSString *text0 = [NSString stringWithFormat:@"%@%@",title0,[BRStringTools br_chargeCardOfTime:dto.chargeCardDuration.integerValue]];
    NSString *couponText = dto.userCouponInfo.deductionType == 1 ? [BRStringTools br_couponTypeTime:dto.userCouponInfo] : [BRPayManager br_amount:dto.couponAmount];
    NSString *text1 = [NSString stringWithFormat:@"%@%@",title1,couponText];
    NSString *promoText = dto.userPromoCodeInfo.deductionType == 1 ? [BRStringTools br_couponTypeTime:dto.userPromoCodeInfo] : [BRPayManager br_amount:dto.promoCodeAmount];
    NSString *text1_1 = [NSString stringWithFormat:@"%@%@",title1_1,promoText];
    NSString *text2 = [NSString stringWithFormat:@"%@%@",title2,[BRPayManager br_amount:dto.plateCouponAmount]];
    
    NSString *text10 = [NSString stringWithFormat:@"%@%@",title10,[BRPayManager br_amount:dto.orderAmount]];
    
    NSString *taxText = [NSString stringWithFormat:@"%@%@",taxTitle,[BRPayManager br_amount:dto.taxAmount]];
    NSString *taxInText = [NSString stringWithFormat:@"%@%@",taxInTitle,[BRPayManager br_amount:dto.money]];
    
    NSString *text7 = [NSString stringWithFormat:@"%@%@",title7,[BRTools getTimeFromTimestamp:dto.createTime.integerValue formatter:kTimeFormatter]];
    NSString *text8 = [NSString stringWithFormat:@"%@%@",title8,[BRTools getTimeFromTimestamp:dto.endTime.integerValue formatter:kTimeFormatter]];
    
    NSInteger duration = dto.useDuration;
    if (self.payType == BRPAY_LOST) {
        duration = dto.endTime.integerValue / 1000 - dto.createTime.integerValue / 1000;
    }
    
    NSString *text9 = [NSString stringWithFormat:@"%@%@",title9,[BRTools getFormatTimeFromDurationTime:duration]];

    
    NSString *text6 = [NSString stringWithFormat:@"%@%@",title6,dto.orderNo];
    
    NSAttributedString *att0 = [BRStringTools br_att:text0 rang:NSMakeRange(title0.length, text0.length - title0.length) textC:kColorTitle];
    NSAttributedString *att1 = [BRStringTools br_att:text1 rang:NSMakeRange(title1.length, text1.length - title1.length) textC:kColorTitle];
    NSAttributedString *att1_1 = [BRStringTools br_att:text1_1 rang:NSMakeRange(title1_1.length, text1_1.length - title1_1.length) textC:kColorTitle];
    NSAttributedString *att2 = [BRStringTools br_att:text2 rang:NSMakeRange(title2.length, text2.length - title2.length) textC:kColorTitle];
//    NSAttributedString *att3 = [BRStringTools br_att:text3 rang:NSMakeRange(title3.length, text3.length - title3.length) textC:kColorTitle];
//    NSAttributedString *att5 = [BRStringTools br_att:text5 rang:NSMakeRange(title5.length, text5.length - title5.length) textC:kColorTitle];
    NSAttributedString *att6 = [BRStringTools br_att:text6 rang:NSMakeRange(title6.length, text6.length - title6.length) textC:kColorTitle];
    NSAttributedString *att7 = [BRStringTools br_att:text7 rang:NSMakeRange(title7.length, text7.length - title7.length) textC:kColorTitle];
    NSAttributedString *att8 = [BRStringTools br_att:text8 rang:NSMakeRange(title8.length, text8.length - title8.length) textC:kColorTitle];
    NSAttributedString *att9 = [BRStringTools br_att:text9 rang:NSMakeRange(title9.length, text9.length - title9.length) textC:kColorTitle];
   
    NSAttributedString *att10 = [BRStringTools br_att:text10 rang:NSMakeRange(title10.length, text10.length - title10.length) textC:kColorTitle];
    NSAttributedString *attTax = [BRStringTools br_att:taxText rang:NSMakeRange(taxTitle.length, taxText.length - taxTitle.length)  textC:kColorTitle];
    NSAttributedString *attTaxIn = [BRStringTools br_att:taxInText rang:NSMakeRange(taxInTitle.length, taxInText.length - taxInTitle.length)  textC:kColorTitle];
    
    [self.detailView.topStack1 br_attText:att0 by:0];
    [self.detailView.topStack1 br_attText:att1 by:1];
    [self.detailView.topStack1 br_attText:att1_1 by:2];
    [self.detailView.topStack1 br_attText:att2 by:3];
    
//    [self.detailView.topStack2 br_attText:att3 by:0];
//    [self.detailView.topStack2 br_attText:att5 by:1];
    
    [self.detailView.centStack br_attText:att6 by:0];
    [self.detailView.centStack br_attText:att7 by:1];
    [self.detailView.centStack br_attText:att8 by:2];
    [self.detailView.centStack br_attText:att9 by:3];
    [self.detailView.centStack br_attText:att10 by:4];
    [self.detailView.centStack br_attText:attTax by:5];
    [self.detailView.centStack br_attText:attTaxIn by:6];
    
    [self.detailView.centStack br_textHidden:!hasTax by:5];
//    [self.detailView.centStack br_textHidden:!hasTax by:6];
    
    self.detailView.textPlan.text = [[BRUserManager share] br_ruleOfModel:dto.billing];
    
    BOOL hasChargeCard = dto.chargeCardDuration.integerValue != 0;
    BOOL hasCoupon = dto.userCouponId.length != 0;
    BOOL hasPromo = dto.userPromoCodeId.floatValue != 0;
    BOOL hasDis = dto.plateCouponAmount.floatValue != 0;
    
    [self.detailView.topStack1 br_textHidden:!hasChargeCard by:0];
    [self.detailView.topStack1 br_textHidden:!hasCoupon by:1];
    [self.detailView.topStack1 br_textHidden:!hasPromo by:2];
    [self.detailView.topStack1 br_textHidden:!hasDis by:3];
    
    BOOL hidddenAll = !(hasCoupon || hasPromo || hasDis || hasChargeCard);
    
    self.detailView.hiddenALL = hidddenAll;
    
    //主动报失没有归还时间 或 已丢失
    [self.detailView.centStack br_textHidden:(self.payType == BRPAY_LOST || dto.lost) by:2];
    
}



#pragma mark - 3D绑卡支付API
-(void)sent3Dmethod:(NSString *)clientSecret {

    
    STPPaymentIntentParams *paymentIntentParmas = [[STPPaymentIntentParams alloc] initWithClientSecret:clientSecret];
    if (self.addCardView.paymentMethodCardParams && self.isPayWithCard) {
        STPPaymentMethodCardParams *cardParams = self.addCardView.paymentMethodCardParams;
        STPPaymentMethodParams *paymentMethodParams = [STPPaymentMethodParams paramsWithCard:cardParams billingDetails:nil metadata:nil];
        paymentIntentParmas.paymentMethodParams = paymentMethodParams;
    }
    
    
    [[STPPaymentHandler sharedHandler] confirmPayment:paymentIntentParmas withAuthenticationContext:self completion:^(enum STPPaymentHandlerActionStatus status, STPPaymentIntent * _Nullable paymentIntent, NSError * _Nullable error) {
        
        [BRHud hiddenInView:self.view];
        if (status == STPPaymentHandlerActionStatusSucceeded) {
            //支付成功

            
            [self payStatus:BRPAY_SUCC by:self.paymentModel];
            
        }else if(status == STPPaymentHandlerActionStatusFailed){
            //支付失败
            
            //错误状态的本地化描述
            NSString *localizedDescription = error.localizedDescription;
            if (BR_StringIsEmpty(localizedDescription)) {
                self.paymentModel.failedReason = Localized(@"Pay_Page_payment_failed");
            }else {
                
                self.paymentModel.failedReason = [NSString stringWithFormat:@"AT-%@(%ld)",localizedDescription,(long)error.code];
            }
            
//            vc.dto = self.paymentModel;
//            [self.navigationController pushViewController:vc animated:YES];
            
            [self payStatus:BRPAY_FAILED by:self.paymentModel];
            
        }
    }];
}

/*
 * 3D验证成功，校验回调
 */
-(void)callbackCheckStripe:(NSString *)sourceId
{
//    WS(weakSelf);
//    [[NetWorkRequest shared] checkPaymentStripeResult:sourceId succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
//        [weakSelf isTipSuccess:weakSelf.paymentModel];
        
//    } failed:^(NSError * _Nonnull error) {
        
        //
//        [weakSelf postActionErrorWithContent:[NSString stringWithFormat:@"AT-%@(%ld)",error.localizedDescription,error.code]];
//    }];
}
#pragma mark - STPAuthenticationContext
- (UIViewController*)authenticationPresentingViewController
{
    return self;
}

#pragma mark - tableView Delegate --
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cardList.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    BRCardListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRCardListTableViewCell"];
    
    
    if (indexPath.row == 0) {
        cell.type  = 0;
        return cell;
    }
    cell.type = 1;
    cell.isSel = (indexPath.row == _cardSelectIndex + 1);
    BRCardModel *model = self.cardList[indexPath.row - 1];
    cell.dto = model;
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        [BRHud showInView:self.view];
        WS(weakSelf);
        [self req_payFirst:^(id dic) {
            [BRHud hiddenInView:weakSelf.view];
            [weakSelf toCardPay];
        }];
        
    }else {
        
        for (int i = 1; i < self.cardList.count + 1; i++) {
            NSIndexPath *iPath = [NSIndexPath indexPathForRow:i inSection:0];
            BRCardListTableViewCell *cell = (BRCardListTableViewCell *)[tableView cellForRowAtIndexPath:iPath];
            
            cell.isSel = i == indexPath.row ? YES : NO;
            
        }
        _cardSelectIndex =  indexPath.row - 1;
    }
}

#pragma mark - SET UI --
- (void)setUI  {
    
    BOOL isCouponOn = self.payType == BRPAY_Rent && !self.dto.lost;
    if (self.dto) {
        if (self.dto.lost) isCouponOn  = NO;
    }
    CGFloat content_y = 134 + kSafeAreaTopHeight + 8;
    CGFloat lineBottom = 66;
    if (isCouponOn) {
        content_y += 44;
        lineBottom += 44;
    }
    
    BRNavView *top = [self br_createTop:Localized(@"home_payment")];
    top.mj_h = content_y;
    top.popView.hidden = NO;
    
    
    UIView *line = [BRToolsView getLineView:UIColorMakeWithHex(@"#D2D8E2")];
    line.alpha = 0.62;
    [top addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.bottom.offset(-lineBottom);
        make.left.offset(28);
        make.right.offset(-28);
    }];
    line.hidden = YES;
    
    UIColor *payTitleColor = kColorTitle;
    
    UIView *amountBg = [UIView new];
    [top addSubview:amountBg];
    [amountBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(76);
        make.left.offset(0);
        make.right.offset(0);
        make.bottom.equalTo(line.mas_top).offset(0);
    }];
    
    NSString *amountStr =[BRPayManager br_amount:self.amount];
    QMUILabel *amountL = [BRToolsView br_label:amountStr textColor:payTitleColor font:[UIFont fontB:37]];
    [amountBg addSubview:amountL];
    [amountL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.centerY.offset(0);
    }];
    _balanceL = amountL;
    
    self.taxLb = [BRToolsView br_label:[NSString stringWithFormat:@"(%@--%%)",Localized(@"pay_includingTax")] textColor:payTitleColor font:[UIFont fontM:10]];
    [top addSubview:self.taxLb];
    [self.taxLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(amountL.mas_bottom).offset(4);
    }];
//    self.taxLb.hidden = self.payType != BRPAY_ChargeCard;
    self.taxLb.hidden = YES;
    
    UIStackView *pendStack = [[UIStackView alloc] init];
    pendStack.spacing = 4;
    [top addSubview:pendStack];
    [pendStack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(44);
        make.centerX.offset(0);
        make.top.equalTo(line.mas_bottom).offset(0);
    }];
    
    
    NSString *str = @"--";
    switch (self.payType) {
        case BRPAY_Deposit:
            str = Localized(@"wallet_deposit");
            break;
        case BRPAY_Rent:
            str = Localized(@"pay_rental");
            break;
        case BRPAY_LOST:
            str = Localized(@"pay_powerbank");
            break;
      
        default:
            break;
    }
    if (self.dto.lost) {
        str = Localized(@"pay_powerbank");
    }
    
    QMUILabel *pendL = [BRToolsView br_label:[NSString stringWithFormat:@"%@: %@",Localized(@"home_for"),str] textColor:payTitleColor font:[UIFont fontM:14]];
    [pendStack addArrangedSubview:pendL];
    QMUIButton *btnWaring = [[QMUIButton alloc] init];
    [btnWaring setImage:UIImageMake(@"pay_details") forState:UIControlStateNormal];
    btnWaring.frame = CGRectMake(0, 0, 24, 44);
    [pendStack addArrangedSubview:btnWaring];
    btnWaring.hidden = (self.payType == BRPAY_Deposit);
//    [btnWaring addTarget:self action:@selector(showOrderDetail) forControlEvents:UIControlEventTouchUpInside];
    
    UIControl *showBtn = [[UIControl alloc] init];
    [top addSubview:showBtn];
    [showBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(44);
        make.centerX.equalTo(btnWaring.mas_centerX);
        make.centerY.equalTo(btnWaring.mas_centerY);
    }];
    [showBtn addTarget:self action:@selector(showOrderDetail) forControlEvents:UIControlEventTouchUpInside];
    showBtn.hidden = btnWaring.isHidden;
    
    self.couponBgView.hidden = !isCouponOn;
    [top addSubview:self.couponBgView];
    [self.couponBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(44);
        make.left.offset(0);
        make.right.offset(0);
        make.top.equalTo(pendStack.mas_bottom).offset(0);
    }];
    //------------- 内容区域 -----------
    UIView *contentView = [[UIView alloc] init];
    contentView.backgroundColor = UIColor.clearColor;
    [self.view addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset((content_y));
    }];
    [contentView  layoutIfNeeded];
    // 设置顶部圆角
    // 绘制圆角 需设置的圆角 使用"|"来组合
//    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:contentView.bounds byRoundingCorners:UIRectCornerTopLeft |
//    UIRectCornerTopRight cornerRadii:CGSizeMake(25, 25)];
//    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
//
//    // 设置大小
//    maskLayer.frame = contentView.bounds;
//
//    // 设置图形样子
//    maskLayer.path = maskPath.CGPath;
//    contentView.layer.mask = maskLayer;
    
    
    [contentView addSubview:self.tableView];
    // content_y + 16 + 76  = 276 content_y  swap + 74
    self.tableView.frame = CGRectMake(0, 20, kScreenWidth, kScreenHeight - (content_y + 80 + kSafeAreaBottomHeight));
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 72.0;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRCardListTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRCardListTableViewCell"];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    CGFloat h = (self.payType == BRPAY_Deposit) ? 72 : 22;
    UIView *foot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, h)];
    self.tableView.tableFooterView = foot;
    //让addview 早于底部按钮添加
    [self.view addSubview:self.addCardView];
    
    // ------------------------
    UIView *submitView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - (kSafeAreaBottomHeight + 82), kScreenWidth, (kSafeAreaBottomHeight + 82) )];
    submitView.backgroundColor = self.payType == BRPAY_Deposit ? UIColor.whiteColor : UIColor.clearColor;
    [self.view addSubview:submitView];
    _payBgView = submitView;
    [submitView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.bottom.offset(0);
    }];
    
    UIStackView *stack = [[UIStackView alloc] init];
    stack.axis = UILayoutConstraintAxisVertical;
    stack.spacing = 12;
    [submitView addSubview:stack];
    [stack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(12);
        make.left.offset(14);
        make.bottom.offset(-(12 + kSafeAreaBottomHeight));
        make.right.offset(-14);
    }];
    
    
    QMUIButton *submitBtn = [BRToolsView br_btnBGImg:Localized(@"home_gotoPay")];
    _submitBtn = submitBtn;
//    [submitView addSubview:submitBtn];
//    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.height.mas_equalTo(52);
//        make.width.mas_equalTo(kScreenWidth - 56);
//        make.centerX.equalTo(self.view);
//        make.top.equalTo(submitView.mas_top).offset(15);
//    }];
    [submitBtn addTarget:self action:@selector(goToPay) forControlEvents:UIControlEventTouchUpInside];
    
    
    if (self.payType == BRPAY_Deposit) {
        [self.view addSubview:self.depositView];
        
    }else {
        [self.view addSubview:self.detailView];
        [self.detailView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        
        }];
        [self.view bringSubviewToFront:self.detailView];
        [self.view bringSubviewToFront:self.navView];
    }
    self.hasCoupon = isCouponOn;
    if (isCouponOn) {
        [self.view addSubview:self.couponView];
       
    }
    
    if (self.payType != BRPAY_Deposit) {
        
        [stack addArrangedSubview:submitBtn];
        [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(52);
        }];
        return;
    }
    // 协议 -------------
    UIView *agreeBG = [[UIView alloc] init];
    
    [stack addArrangedSubview:agreeBG];
    [stack addArrangedSubview:submitBtn];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
    }];
    
    YYLabel *agreeMsg = [YYLabel new];
    agreeMsg.font = [UIFont br_fontM:11];
    agreeMsg.numberOfLines = 0;
    agreeMsg.preferredMaxLayoutWidth = kScreenWidth - 100;//100
    agreeMsg.textAlignment = NSTextAlignmentLeft;
    [agreeBG addSubview:agreeMsg];
    [agreeMsg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(40);
        make.right.offset(0);
        make.bottom.top.offset(0);
        make.height.mas_greaterThanOrEqualTo(16);
    }];
    WS(weakSelf);
    NSString *agreeStr = Localized(@"login_agreeTo");
    NSString *terms = Localized(@"agreement_deposit");
   
    agreeMsg.text = [NSString stringWithFormat:@"%@%@",agreeStr,terms];
    NSMutableAttributedString *agreeAttStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",agreeStr,terms]];
    
    UIColor *titleColor = UIColor.qd_titleTextColor2;
    [agreeAttStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(agreeStr.length, terms.length) ];
    agreeAttStr.yy_color = titleColor;
    agreeAttStr.yy_font = [UIFont br_fontM:10];
    [agreeAttStr yy_setTextHighlightRange:NSMakeRange(agreeStr.length, terms.length) color: titleColor backgroundColor:UIColor.whiteColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf toPolicy];
        NSLog(@"0");
    }];
    agreeMsg.attributedText = agreeAttStr;
    [agreeMsg sizeToFit];
    
    UIButton *policyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [policyBtn setImage:[UIImage imageNamed:@"set_unagree"] forState:UIControlStateNormal];
    [policyBtn setImage:[UIImage imageNamed:@"set_agree"] forState:UIControlStateSelected];
    [agreeBG addSubview:policyBtn];
    [policyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(16);
        make.top.equalTo(agreeMsg.mas_top).offset(0);
        make.right.equalTo(agreeMsg.mas_left).offset(-8);
    }];
    
    policyBtn.userInteractionEnabled = NO;
    policyBtn.selected = YES;
    _policyBtn = policyBtn;
    
    UIControl *btn = [[UIControl alloc] init];
    [submitView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(policyBtn);
        make.width.height.mas_equalTo(50);
        make.centerY.equalTo(policyBtn);
    }];
    [btn addTarget:self action:@selector(clickPolicyBtn:) forControlEvents:UIControlEventTouchUpInside];
}

- (BRPayDetailPopView *)detailView {
    
    if (_detailView == nil) {
        _detailView = [[BRPayDetailPopView alloc] initWithType:self.payType isLost:self.dto.lost];
        
        _detailView.hidden = YES;
    }
    return _detailView;
}

- (BRPaymentDetailView *)addCardView {
    if (_addCardView == nil) {
        _addCardView = [[BRPaymentDetailView alloc] initAddViewWithFrame:self.view.bounds];
    }
    return _addCardView;
}

- (BRPaymentDetailView *)depositView {
    
    if (_depositView == nil) {
        _depositView = [[BRPaymentDetailView alloc] initDepositWithFrame:self.view.bounds];
    }
    
    return _depositView;
}

- (BRCouponUseListView *)couponView {
    
    if (_couponView == nil) {
        _couponView = [[BRCouponUseListView alloc] initWithFrame:self.view.bounds];
    }
    return _couponView;
}

- (UIView *)couponBgView {
    
    if (_couponBgView == nil) {
        _couponBgView = [[UIView alloc] init];
        _couponBgView.hidden = YES;
        _couponBgView.backgroundColor = UIColor.clearColor;
        UIView *line = [BRToolsView getLineView:UIColorMakeWithHex(@"#D2D8E2")];
        line.alpha = 0.62;
        [_couponBgView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(0);
            make.height.mas_equalTo(0.5);
            make.left.offset(28);
            make.right.offset(-28);
        }];
        
        //如果可以使用优惠券
        UIStackView *stackView = [[UIStackView alloc] init];
        stackView.axis = UILayoutConstraintAxisHorizontal;
        stackView.distribution = UIStackViewDistributionEqualSpacing;
        stackView.spacing = 0;
        CGFloat stack_h = 44;
        
        QMUILabel *lab1 = [BRToolsView br_label:[NSString stringWithFormat:@"%@: ",Localized(@"menu_coupon")] textColor:kColorMain font:[UIFont br_fontM:14]];
        
        [stackView addArrangedSubview:lab1];
    //    _tenantNameL = lab;
        [lab1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_lessThanOrEqualTo(200);
        }];
        
        QMUILabel *lab = [BRToolsView br_label:Localized(@"payment_choose") textColor:kColorMain font:[UIFont br_fontM:14]];
        [stackView addArrangedSubview:lab];
    //    _tenantNameL = lab;
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_lessThanOrEqualTo(200);
        }];
        _couponSelL = lab;
        
        UIView *tenanV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 28, stack_h)];
        UIImageView *rightImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 6, stack_h)];
        rightImg.image = UIImageMake(@"arrow_right_green6");
        rightImg.contentMode = UIViewContentModeRight;
        [tenanV addSubview:rightImg];
        [rightImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(tenanV);
            make.height.mas_equalTo(10);
            make.width.mas_equalTo(6);
            make.centerY.equalTo(tenanV);
        }];


        [stackView addArrangedSubview:tenanV];
        [tenanV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(stack_h);
            make.width.mas_equalTo(12);
        }];
        
        [_couponBgView addSubview:stackView];
        [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.offset(0);
            make.height.mas_equalTo(44);
            make.centerY.offset(0);
        }];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toCouponList)];
        [_couponBgView addGestureRecognizer:tap];
    }
    
    return _couponBgView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
